package cn.gp.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 *@Description 配置mybatis
 *@Return null
 *@Author He_Guoping
 *@Date 13:29 2023/5/24
 */
public class MybatisConfig {
    /*
    @PostConstruct
    public void init() {
        org.apache.ibatis.logging.LogFactory.useLog4JLogging();
    }
     */

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource, PageInterceptor pageInterceptor) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();

        // 配置日志
        config.setLogImpl(Log4jImpl.class);

        // 开启驼峰命名自动映射
        config.setMapUnderscoreToCamelCase(true);

        // 分页插件
        sqlSessionFactoryBean.setPlugins(pageInterceptor);

        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("cn.gp.entity");
        sqlSessionFactoryBean.setConfiguration(config);

        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("cn.gp.mapper");
        return mapperScannerConfigurer;
    }

    /**
     *@Description pagehelper拦截器
     *@Return com.github.pagehelper.PageInterceptor
     *@Author He_Guoping
     *@Date 12:23 2023/5/31
     */
    @Bean
    public PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("param1", "value1");
        pageInterceptor.setProperties(properties);
        return pageInterceptor;
    }

}
